var express = require('express');
var path = require('path');

var app = express();
var fs = require('fs');
//

import React from 'react'
import ReactDOMServer from 'react-dom/server'
import {StaticRouter} from 'react-router-dom'
import App from './ServerApp'

app.use(express.static(path.join(__dirname, 'public')));
app.get('*', function (req, res) {
    const context = {}
    console.log(req.url);

    const html = ReactDOMServer.renderToString(
        <StaticRouter
            location={req.url}
            context={context}
        >
            <App/>
        </StaticRouter>
    )

    if (context.url) {
        res.writeHead(301, {
            Location: context.url
        })
        res.end()
    } else {
        res.setHeader("Content-Type", 'text/html;charset=utf-8');
        res.write(`
      <!DOCTYPE html><html><head><meta charset='UTF-8'><link href="${__dirname}/public/style.css" rel="stylesheet"></head><body>
      <div id="app">${html}</div></body></html>
    `)
        res.end()
    }
}).listen(3000);

// createServer((req, res) => {
//     const context = {}
//     console.log(req.url);
//     const html = ReactDOMServer.renderToString(
//         <StaticRouter
//             location={req.url}
//             context={context}
//         >
//             <App/>
//         </StaticRouter>
//     )
//
//     if (context.url) {
//         res.writeHead(301, {
//             Location: context.url
//         })
//         res.end()
//     } else {
//         res.setHeader("Content-Type", 'text/html;charset=utf-8');
//         res.write(`
//       <!DOCTYPE html><html><head><meta charset='UTF-8'><link href="style.css" rel="stylesheet"></head><body>
//       <div id="app">${html}</div></body></html>
//     `)
//         res.end()
//     }
// }).listen(3000)

// https://facebook.github.io/react/docs/react-dom-server.html#rendertostring
// https://reacttraining.com/react-router/web/api/StaticRouter